//
//  WBpopView.swift
//  SainMicroblog
//
//  Created by chenxinju on 16/5/10.
//  Copyright © 2016年 chenxinju-a2. All rights reserved.
//

import UIKit
import pop
import SnapKit

class WBpopView: UIView {
    //定义一个跳转控制器的属性
    var target: UIViewController?
    
    //按钮属性
    private lazy var composeButton:[UIButton] = [UIButton]()
   override init(frame: CGRect) {
        super.init(frame: frame)
      self.frame.size = CGSizeMake(WBUIScreenW, WBUIScreenH)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupUI() {
        backgroundColor = UIColor.yellowColor()
        addSubview(bgImageView)
        bgImageView.snp_makeConstraints { (make) -> Void in
          
          make.edges.equalTo(self.snp_edges)
        }
        
        //添加按钮
        addchildButtons()
        
    }
    
    private func addchildButtons() {
    
        let maxClo = 3
        //按钮的宽高
        let childButtonW:CGFloat = 80
        let childButtonH:CGFloat = 110
        
        //按钮的间距
        let margin = (WBUIScreenW - CGFloat(maxClo) * childButtonW) / CGFloat(maxClo + 1)
        
        //读取plist
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        
        let composeButtonInfos = NSArray(contentsOfFile: path)!
        //遍历
        for i in 0..<composeButtonInfos.count{
            let popButton = WBPopButton()
            //添加点击动画
            popButton.addTarget(self, action: "showDetailVc:", forControlEvents: UIControlEvents.TouchUpInside)
            //设置按钮的宽
            popButton.frame.size = CGSizeMake(childButtonW, childButtonH)
            let col = i % maxClo
            let row = i / maxClo
            popButton.frame.origin.x = margin * CGFloat(col + 1) + childButtonW * CGFloat(col)
            popButton.frame.origin.y = margin * CGFloat(row + 1) + childButtonH * CGFloat(row) + WBUIScreenH

            
            //拿到数据
            let dic = composeButtonInfos[i] as! [String: AnyObject]
            
            let title = dic["title"] as? String
            
            let icon = dic["icon"] as! String
            
            popButton.setTitle(title, forState: UIControlState.Normal)
            
            popButton.setImage(UIImage(named: icon), forState: UIControlState.Normal)
            addSubview(popButton)
            composeButton.append(popButton)
        }
    }
    

    class func testShow(target: UIViewController?) {
        WBpopView().show(target)
    }

    //动画点击效果
    private func show(target: UIViewController?) {
      self.target = target
        self.target?.view.addSubview(self)
        for (index,button) in composeButton.enumerate(){
          anim(button, beginTime: CACurrentMediaTime() + Double(index) * 0.04, isUp: true)
        }
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        
        for (index,button) in composeButton.enumerate(){
            anim(button, beginTime: CACurrentMediaTime() + Double(index) * 0.04, isUp: false)
        }
        // removeFromSuperview要延迟一下
        
        // NSEC_PER_SEC 这个纳秒，这个不需要记忆
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.3 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            
            self.removeFromSuperview()
        }
    }
    
    
    
    //抽取的代码
    func anim(button:UIButton, beginTime:Double,isUp:Bool){
        /*
        public let kPOPViewAlpha: String
        public let kPOPViewBackgroundColor: String
        public let kPOPViewBounds: String
        public let kPOPViewCenter: String
        public let kPOPViewFrame: String
        public let kPOPViewScaleX: String
        public let kPOPViewScaleXY: String
        public let kPOPViewScaleY: String
        public let kPOPViewSize: String
        public let kPOPViewTintColor: String
        */
      let anmation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        
        if isUp {
            anmation.toValue = NSValue(CGPoint: CGPoint(x: button.center.x, y: button.center.y - 300))
        }else {
    
         anmation.toValue = NSValue(CGPoint: CGPoint(x: button.center.x, y: button.center.y + 300))
        }
        
        
        //弹簧的速度
        anmation.springSpeed = 10
        
        //弹簧的力度
        anmation.springBounciness = 9
        
        //设置动画开始的时间
        anmation.beginTime = beginTime
        //添加到视图
        button.pop_addAnimation(anmation, forKey: nil)
    }
    
    
    
    //按钮点击方法
    func showDetailVc(button:WBPopButton) {

        UIView.animateWithDuration(0.25, animations: { () -> Void in
            
            for bt in self.composeButton {
                
                bt.alpha = 0
                
                if bt == button {
                    
                    button.transform = CGAffineTransformMakeScale(1.5,1.5)
                    
                    
                } else {
                    
                    bt.transform = CGAffineTransformMakeScale(0.3,0.3)
                    
                    
                }
                
            }
            
            }) { (_) -> Void in
                
                // 当动画完成之后，怎么办 控制器的跳转
                // 视图消失
                self.removeFromSuperview()
                
                // 实际开发过程中，经常用到方法，就是把 控制传递到 view这里，然后进行页面控制器的跳转
                let publish = WBPublishViewController()
                let nav = UINavigationController(rootViewController: publish)
                self.target?.presentViewController(nav, animated: true, completion: { () -> Void in
                    
                })
        }
}
    
    
//    mark懒加载King控件

   private lazy var bgImageView: UIImageView = {
    
      let image = UIImageView()
    
       image.image = UIImage.getScreenShot()
    
    //毛玻璃效果
    let effect = UIBlurEffect(style: UIBlurEffectStyle.Light)
    let effectView = UIVisualEffectView(effect: effect)
     //把毛玻璃添加到图片上
    image.addSubview(effectView)
    //设置约束
    effectView.snp_makeConstraints(closure: { (make) -> Void in
        make.edges.equalTo(image.snp_edges)
        
    })
    
       return image
    
    }()

}
